package br.com.abelha.manager.validator;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import org.xmlpull.v1.XmlSerializer;

import android.os.Environment;
import android.util.Xml;
import br.com.abelha.manager.entity.FichaB;
import br.com.abelha.manager.ws.RequestAbelhaService;

public class FichasParserXml {

	private XmlSerializer serializer;
	public Object clazz;
	private boolean comeFromFichaB;

	private String idFichaA;
	private String idPaciente;
	private String idFichaB;

	public FichasParserXml(Object a) {
		this.clazz = a;
	}

	public String generateXml() {

		serializer = Xml.newSerializer();
		FileOutputStream fileos = null;
		File newxmlfile = new File(Environment.getExternalStorageDirectory(),
				"new.xml");

		try {
			newxmlfile.createNewFile();
			fileos = new FileOutputStream(newxmlfile);
			serializer.setOutput(fileos, "UTF-8");
			serializer.startDocument(null, Boolean.valueOf(true));

			serializer.startTag(null, "root");
			Class<?> c = clazz.getClass();

			Field[] fields = c.getDeclaredFields();
			boolean toCheck = false;
			
			for (int i = 0; i < fields.length; i++) {

				if (!Modifier.isStatic(fields[i].getModifiers())) {

					if (!toCheck) {
						if (comeFromFichaB) {

							serializer.startTag(null, "id");
							serializer.text(idFichaB);
							serializer.endTag(null, "id");

							serializer.startTag(null, "id_paciente");
							serializer.text(idPaciente);
							serializer.endTag(null, "id_paciente");

							serializer.startTag(null, "id_fichaa");
							serializer.text(idFichaA);
							serializer.endTag(null, "id_fichaa");

						}
					}
					
					toCheck = true;
					serializer.startTag(null, fields[i].getName());

					/**
					 * Instance of...
					 */

					fields[i].setAccessible(true);

					if (fields[i].get(clazz) != null) {
						serializer.text(fields[i].get(clazz).toString());
					} else {
						fields[i].set(clazz, "");
					}

					serializer.endTag(null, fields[i].getName());

				}

			}

			serializer.endTag(null, "root");
			serializer.endDocument();
			serializer.flush();
			fileos.close();

			String result = new RequestAbelhaService()
					.uri("http://10.0.0.5/PFS/posts/postfichac.aspx")
					.xml(newxmlfile).timeout(9000).post();
			System.out.println(result);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;

	}

	public boolean isComeFromFichaB() {
		return comeFromFichaB;
	}

	public void setComeFromFichaB(boolean comeFromFichaB) {
		this.comeFromFichaB = comeFromFichaB;
	}

	public String getIdFichaA() {
		return idFichaA;
	}

	public void setIdFichaA(String idFichaA) {
		this.idFichaA = idFichaA;
	}

	public String getIdPaciente() {
		return idPaciente;
	}

	public void setIdPaciente(String idPaciente) {
		this.idPaciente = idPaciente;
	}

	public String getIdFichaB() {
		return idFichaB;
	}

	public void setIdFichaB(String idFichaB) {
		this.idFichaB = idFichaB;
	}

}
